//
//  HXPersonListTableViewController.m
//  KD
//
//  Created by ifly on 16/5/16.
//  Copyright © 2016年 Whx. All rights reserved.
//

#import "HXPersonListTableViewController.h"
#import "NetworkAPI.h"
#import "HXPersonNumModel.h"
#import "HXPersonListTableViewCell.h"
#import "JCHATConversationListViewController.h"
#import "JCHATConversationViewController.h"

@interface HXPersonListTableViewController ()<UITableViewDelegate,UITableViewDataSource>

@property(nonatomic,strong)HXPersonNumListModel *personListData;
@property(nonatomic,strong)NSMutableArray<HXPersonNumListModel *> *personListDataArray;
@property(nonatomic,strong)NSMutableArray<HXPersonNumListDetaiksModel *> *personListDateilsDataArray;
@property(nonatomic,strong)NSMutableArray<HXPersonNumListDetaiksModel *> *personArray;
@property(nonatomic,strong)NSMutableArray *stateArray;
@property(nonatomic,strong)UIView * backgroundView;
@property(nonatomic,strong)UIWindow * window;
@property(nonatomic,assign)NSInteger rowNum;
@property(nonatomic,assign)NSInteger sectionNum;
@end

@implementation HXPersonListTableViewController

//static id _instace;
//////遗留问题
//+ (instancetype)sharedPersonVc
//{
//    static dispatch_once_t onceToken;
//    dispatch_once(&onceToken, ^{
//        _instace = [[self alloc] init];
//    });
//    return _instace;
//}
//
//+ (id)allocWithZone:(struct _NSZone *)zone
//{
//    static dispatch_once_t onceToken;
//    dispatch_once(&onceToken, ^{
//        _instace = [super allocWithZone:zone];
//    });
//    return _instace;
//}
//
//- (id)copyWithZone:(NSZone *)zone
//{
//    return _instace;
//}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.tableView.tableFooterView = [[UIView alloc]init];
    self.tableView.mj_header=[AWRefreshHeader headerWithRefreshingTarget:self refreshingAction:@selector(refreshData)];
    _personListDataArray = [[NSMutableArray alloc] init];
    _personListDateilsDataArray = [[NSMutableArray alloc] init];
    _stateArray = [[NSMutableArray alloc] init];
    [self.tableView.mj_header beginRefreshing];
    self.tableView.frame = CGRectMake(0, 64, HXSCREEN_WIDTH, SCREEN_HEIGHT);
//    [NetworkAPI getPersonListWithType:@"deptper"
//                                Ckind:@""
//                              Success:^(HXPersonNumModel *result) {
//                                  [_personListDataArray addObjectsFromArray:result.resultlist];
//                                  [self.tableView reloadData];
//                                  
//    }
//                              failure:^(NSError *err) {
//        
//    }];
//    
//    [NetworkAPI getPersonListWithType:@"groupper"
//                                Ckind:@""
//                              Success:^(HXPersonNumModel *result) {
//                                  [_personListDataArray addObjectsFromArray:result.resultlist];
//                                  [self.tableView reloadData];
//                              }
//                              failure:^(NSError *err) {
//                                  
//                              }];
    [self.tableView registerNib:[UINib nibWithNibName:@"HXPersonListTableViewCell" bundle:nil] forCellReuseIdentifier:@"HXPersonListTableViewCell"];
    
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    if ([self.isInsert isEqualToString:@"yes"]) {
        self.automaticallyAdjustsScrollViewInsets = NO;
        self.navigationController.navigationBar.translucent = YES;
    }
}
-(void)refreshData {
    
    /**
     [SVProgressHUD showErrorWithStatus:@"网络错误"];
     [SVProgressHUD showSuccessWithStatus:@"获取通知成功"];
     */
    [SVProgressHUD showWithStatus:@"正在加载"];
    
    [NetworkAPI getPersonListWithType:@"deptper"
                                Ckind:@""
                              Success:^(HXPersonNumModel *result) {
                                  if ([result.code isEqualToString:@"200"]) {
                                      [_personListDataArray removeAllObjects];
                                      [_personListDataArray addObjectsFromArray:result.resultlist];
                                      [self.tableView reloadData];
                                      [SVProgressHUD showSuccessWithStatus:@"刷新成功"];
                                      [self.tableView.mj_header endRefreshing];
                                  }
                                  if ([result.code isEqualToString:@"400"]) {
                                      [self.tableView.mj_header endRefreshing];

                                  }
                                  if ([result.code isEqualToString:@"500"]) {
                                      [SVProgressHUD showErrorWithStatus:@"网络错误"];
                                      [self.tableView.mj_header endRefreshing];
                                  }
                              }
                              failure:^(NSError *err) {
                                  [SVProgressHUD showErrorWithStatus:@"网络请求失败"];
                                  [self.tableView.mj_header endRefreshing];
                              }];
    
    [NetworkAPI getPersonListWithType:@"groupper"
                                Ckind:@""
                              Success:^(HXPersonNumModel *result) {
                                  if ([result.code isEqualToString:@"200"]) {
                                      [_personListDataArray removeAllObjects];
                                      [_personListDataArray addObjectsFromArray:result.resultlist];
                                      [self.tableView reloadData];
                                      [SVProgressHUD showSuccessWithStatus:@"刷新成功"];
                                      [self.tableView.mj_header endRefreshing];
                                  }
                                  if ([result.code isEqualToString:@"400"]) {
                                      [self.tableView.mj_header endRefreshing];
                                      
                                  }
                                  if ([result.code isEqualToString:@"500"]) {
                                      [SVProgressHUD showErrorWithStatus:@"网络错误"];
                                      [self.tableView.mj_header endRefreshing];
                                  }
                              }
                              failure:^(NSError *err) {
                                  [SVProgressHUD showErrorWithStatus:@"网络请求失败"];
                                  [self.tableView.mj_header endRefreshing];
                              }];
    [self.tableView registerNib:[UINib nibWithNibName:@"HXPersonListTableViewCell" bundle:nil] forCellReuseIdentifier:@"HXPersonListTableViewCell"];
    
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

//返回多少个分组
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    for (int i = 0; i<self.personListDataArray.count; i++) {
        [_stateArray addObject:[NSNumber numberWithBool:NO]];
    }
    return self.personListDataArray.count;
}
//每个分组返回多少行
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    if ([[_stateArray objectAtIndex:section] boolValue] == NO) {
            return 0;
    }
    HXPersonNumListModel *a = self.personListDataArray[section];
    _personArray = [[NSMutableArray alloc] init];
    [_personArray addObjectsFromArray:a.Person];
    return _personArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    //[self.tableView registerNib:[UINib nibWithNibName:@"HXPersonListTableViewCell" bundle:nil] forCellReuseIdentifier:@"HXPersonListTableViewCell"];
    
    HXPersonListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"HXPersonListTableViewCell" forIndexPath:indexPath];
    HXPersonNumListModel *a = self.personListDataArray[indexPath.section];
    HXPersonNumListDetaiksModel *b = a.Person[indexPath.row];
    cell.data = b;
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 60;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 60;
}

-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    HXPersonNumListModel * a = self.personListDataArray[section -1];
    return a.DeptName;
}

//点击某行跳转
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
//    NSString *isRegister  = [UserDefaultHandler getUserDetault:kIsRegisterJpush];
//    NSString *isLogin  = [UserDefaultHandler getUserDetault:kIsLoginJpush];
//    if (![isLogin isEqualToString:@"yes"]) {
//        UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"提示" message:@"聊天系统正在初始化,请稍后再试" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
//        [alert show];
//    }
    
    
    //自定义view
    _window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    _window.windowLevel =  UIWindowLevelStatusBar + 1;
    _window.hidden = NO;
    _window.backgroundColor = [UIColor clearColor];
    _backgroundView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.window.frame.size.width, self.window.frame.size.height)];
    _backgroundView.backgroundColor = HXCustomColor(0, 0, 0, 0.5);
    [_window addSubview:_backgroundView];
    //添加手势
    UITapGestureRecognizer * clickRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(bvClickRecognizer)];
    [_backgroundView addGestureRecognizer:clickRecognizer];
    UIView * choiceView = [[UIView alloc] initWithFrame:CGRectMake(50, 0, self.view.frame.size.width - 100, 100)];
    choiceView.center = _backgroundView.center;
    choiceView.backgroundColor = [UIColor greenColor];
    [_backgroundView addSubview:choiceView];
    UIButton * oneButton = [UIButton buttonWithType:UIButtonTypeCustom];
    oneButton.frame = CGRectMake(0, 0, choiceView.bounds.size.width, 50);
    oneButton.titleLabel.textAlignment = NSTextAlignmentLeft;
    oneButton.backgroundColor = [UIColor whiteColor];
    [oneButton addTarget:self action:@selector(buttonOneClicked:) forControlEvents:UIControlEventTouchUpInside];
    [oneButton setTitle:@"聊天" forState:UIControlStateNormal];
    [oneButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    oneButton.titleLabel.font = [UIFont systemFontOfSize:20];
    [choiceView addSubview:oneButton];
    UIButton * Twobutton = [UIButton buttonWithType:UIButtonTypeCustom];
    Twobutton.frame = CGRectMake(0, 50, choiceView.bounds.size.width, 50);
    [Twobutton addTarget:self action:@selector(buttonTwoClicked:) forControlEvents:UIControlEventTouchUpInside];
    [Twobutton setTitle:@"拨打电话" forState:UIControlStateNormal];
    Twobutton.backgroundColor = [UIColor whiteColor];
    Twobutton.titleLabel.font = [UIFont systemFontOfSize:20];
    [Twobutton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    Twobutton.titleLabel.textAlignment = NSTextAlignmentCenter;
    [choiceView addSubview:Twobutton];
    
    _rowNum = indexPath.row;
    _sectionNum = indexPath.section;
//    HXPersonNumListModel *a = _personListDataArray[indexPath.section];
//    HXPersonNumListDetaiksModel *b = a.Person[indexPath.row];
//    [[JCHATAlertViewWait ins] showInView];
//    __block JCHATConversationViewController *sendMessageCtl = [[JCHATConversationViewController alloc] init];
//    sendMessageCtl.superViewController = self;
//    sendMessageCtl.hidesBottomBarWhenPushed = YES;
//    __weak __typeof(self)weakSelf = self;
//    [JMSGConversation createSingleConversationWithUsername:b.MIUserName completionHandler:^(id resultObject, NSError *error) {
//        [[JCHATAlertViewWait ins] hidenAll];
//        if (error == nil) {
//            [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
//            __strong __typeof(weakSelf) strongSelf = weakSelf;
//            sendMessageCtl.conversation = resultObject;
//            sendMessageCtl.myTitle = b.MIPersonName;
//            [strongSelf.navigationController pushViewController:sendMessageCtl animated:YES];
//        } else {
//            DDLogDebug(@"createSingleConversationWithUsername fail");
//            [MBProgressHUD showMessage:[JCHATStringUtils errorAlert:error] view:self.view];
//        }
//    }];
}

-(void)bvClickRecognizer {
    _window.hidden = YES;
}

-(void)buttonOneClicked:(UIButton *)button {
    _window.hidden = YES;
    HXPersonNumListModel *a = _personListDataArray[_sectionNum];
    HXPersonNumListDetaiksModel *b = a.Person[_rowNum];
    [[JCHATAlertViewWait ins] showInView];
    __block JCHATConversationViewController *sendMessageCtl = [[JCHATConversationViewController alloc] init];
    sendMessageCtl.superViewController = self;
    sendMessageCtl.hidesBottomBarWhenPushed = YES;
    __weak __typeof(self)weakSelf = self;
    [JMSGConversation createSingleConversationWithUsername:b.MIUserName completionHandler:^(id resultObject, NSError *error) {
        [[JCHATAlertViewWait ins] hidenAll];
        if (error == nil) {
            [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
            __strong __typeof(weakSelf) strongSelf = weakSelf;
            sendMessageCtl.conversation = resultObject;
            sendMessageCtl.myTitle = b.MIPersonName;
            [strongSelf.navigationController pushViewController:sendMessageCtl animated:YES];
        } else {
            DDLogDebug(@"createSingleConversationWithUsername fail");
            [MBProgressHUD showMessage:[JCHATStringUtils errorAlert:error] view:self.view];
        }
    }];
}
-(void)buttonTwoClicked:(UIButton *)button {
    _window.hidden = YES;
    HXPersonNumListModel *a = _personListDataArray[_sectionNum];
    HXPersonNumListDetaiksModel *b = a.Person[_rowNum];
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithFormat:@"tel://%@",b.MIPhoto]]];
}


-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    UIView * backView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.frame.size.width, 50)];
    backView.backgroundColor = [UIColor whiteColor];
    UIImageView * imageView = [[UIImageView alloc] initWithFrame:CGRectMake(8, 8, 34, 34)];
    imageView.image = [UIImage imageNamed:@"personList"];
    [backView addSubview:imageView];
    
    UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(8, 50, tableView.frame.size.width - 16, 1)];
    lineView.backgroundColor = [UIColor whiteColor];
    [backView addSubview:lineView];
    
    UIButton * button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(0, 0, tableView.frame.size.width, 50);
    [button addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
    
    button.tag = 10 + section;
    HXPersonNumListModel * a = _personListDataArray[section];
    [button setTitle:a.DeptName forState:UIControlStateNormal];
    [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    button.contentHorizontalAlignment = 1;
    button.titleEdgeInsets = UIEdgeInsetsMake(0, 55, 0, 0);
    [backView addSubview:button];
    
    return backView;
}

-(void)buttonClicked:(UIButton *)button {
    
    BOOL ret =[[_stateArray objectAtIndex:button.tag - 10] boolValue];
    [_stateArray replaceObjectAtIndex:button.tag - 10 withObject:[NSNumber numberWithBool:!ret]];
    [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:button.tag - 10] withRowAnimation:UITableViewRowAnimationLeft];
}

@end
